// miniprogram/addActive/add/add.js
const app = getApp()
import activeApi from '../../api/activeApi'
import msgCheck from '../../util/msgCheck'

import imgCheck from '../../util/imgCheck'
import uploadImgList from '../../util/uploadImgList'
import {fishCategory} from '../../util/fish'
import pointApi from '../../api/pointApi'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: '',
    avatarUrl: '',
    nickname: '',
    name: '',
    content: '',
    imgList: [],
    fileList: [],
    date: '',
    isPlace: false,
    address: '',
    category: [],
    fishCategory: fishCategory,

    deleteFiles: []
  },
  pageData: {
    latitude: '',
    longitude: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {

    this.setData({
      action: options.action
    })
    if (options.action == 'update') {

      this.getDetail(options.activeId)
    } else {
      var active = wx.getStorageSync("active")
      wx.removeStorageSync('active')
      if (active) {
        console.log(active)
        this.setData({
          content: active.content,
          imgList: active.imgList,

          date: active.date,

          address: active.address
        })

        this.pageData.latitude = active.location.coordinates[1];
        this.pageData.longitude = active.location.coordinates[0];
      }
    }
  },
  async getDetail(activeId) {
    wx.showLoading({
      mask: true
    })

    var res = await activeApi.getActive(activeId)
    res = res[0]

    wx.hideLoading()

    this.setData({
      name: res.name,
      content: res.content,
      imgList: res.imgList,
      fileList: res.fileList,
      address: res.address,
      active: res,
      date: res.date,
      isPlace: res.isPlace,
      category: res.category
    })
    if (res.location) {
      this.pageData.latitude = res.location.coordinates[1];
      this.pageData.longitude = res.location.coordinates[0];
    }



  },
  dateChange(e) {
    this.data.date = e.detail
  },
  nameChange(e){
    this.data.name = e.detail.value
  },
  fishChange(e) {
    this.setData({ category: e.detail });
  },
  previewImage(e) {
    var url = e.currentTarget.dataset.url
    wx.previewImage({
      urls: this.data.imgList,
      current: url
    })
  },
  chooseLocation() {
    wx.chooseLocation({
      success: (res) => {
        this.setData({
          name: res.name,
          address: res.address
        })
        this.pageData.longitude = res.longitude
        this.pageData.latitude = res.latitude
      }
    })
  
  },
  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },
  bindTimeChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value
    })
  },
  contentInput: function (e) {
    var val = e.detail.value;

    this.setData({
      content: val
    });
  },
  chooseImage: function () {
    wx.chooseMedia({
      count: 9 - this.data.imgList.length,
      mediaType: ['image'],
      success: (res) => {
        let list = res.tempFiles.map(obj => obj.tempFilePath)

        const tempFilePaths = this.data.imgList.concat(list)
        this.setData({
          imgList: tempFilePaths
        })
      }
    })
  },

  delImg(e) {
    this.data.active
    var index = e.currentTarget.dataset.index
    this.data.imgList.splice(index, 1)
    var fileIds = this.data.fileList.splice(index, 1)
    if (fileIds[0]) {
      this.data.deleteFiles.push(fileIds[0])
    }
    this.setData({
      imgList: this.data.imgList
    })
  },

  switchIsPlace(e){
    var val = e.detail.value;
    this.setData({
      isPlace: val
    })
  },



  async addActive() {
    
    if(!this.pageData.longitude){
      wx.showToast({
        title: '请选择地理位置',
        icon: 'none'
      })
      return
    }

    
    let pass = await msgCheck(this.data.content)
    if (!pass) {
      return
    }

    pass = await imgCheck(this.data.imgList)
    if (!pass) {
      return
    }

    wx.showLoading({
      title: '正在提交数据',
      mask: true
    })
    var res = await uploadImgList(this.data.imgList, this.data.fileList)

    var params = {
      openid: app.globalData.openid,
      avatarUrl: wx.getStorageSync('avatarUrl'),
      nickname:  wx.getStorageSync('nickname'),
      name: this.data.name,
      content: this.data.content,
      fileList: res.map((f) => f.fileID),
      imgList: res.map((f) => f.tempFileURL),
      date: this.data.date,
      address: this.data.address,
      isPlace: this.data.isPlace,
      category: this.data.category
    }


    if (this.pageData.longitude) {
      params.longitude = this.pageData.longitude,
        params.latitude = this.pageData.latitude
    }

    if (this.data.action == 'update') {

      params.id = this.data.active._id
      var paramsCopy = JSON.parse(JSON.stringify(params))
      var data = await activeApi.updateActive(params)

      wx.cloud.deleteFile({
        fileList: this.data.deleteFiles
      })



      wx.setStorageSync('updateActiveDate', paramsCopy)
      wx.navigateBack()
    } else {

      var data = await activeApi.addActive(params)
      wx.showToast({
        title: '添加成功',
      })

      pointApi.addNum({
        openid: wx.getStorageSync('openid'),
        num: 100
      })

      params.id = data


      wx.setStorageSync('addActive', 1)
      wx.redirectTo({
        url: '/pages/activeDetail/activeDetail?activeId=' + data
      })
    }
    wx.hideLoading()
  },

  onChooseAvatar(e){
    if(wx.getStorageSync('nickname')){
      this.addActive()
      return
    }
    this.selectComponent('#avatarNickname').open()
   
  },
  avatarNicknameConfirm(e){
   
    this.addActive()
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  //   onShareAppMessage: function () {
  //     return {
  //       title: '这是一个记事本备忘录',
  //       imageUrl: 'https://public-server-center-prod-1258963190.cos.ap-guangzhou.myqcloud.com/studentCard/20210521153238.jpg'
  //     }
  //   }
})